<?php

/**
 * This is the model class for table "{{mem_ticket}}".
 *
 * The followings are the available columns in table '{{mem_ticket}}':
 * @property integer $zmi_id
 * @property integer $zm_id
 * @property integer $zti_id
 * @property integer $zmi_val
 * @property string $zmi_title
 * @property integer $zmi_start_time
 * @property integer $zmi_end_time
 * @property integer $zmi_status
 * @property integer $inputtime
 */
 /*
  *MemTicket::model()->getTicket($zti_id,$num);领取优惠券方法
  */
class MemTicket extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return MemTicket the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{mem_ticket}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zm_id,zmi_condition,zmi_num', 'numerical', 'integerOnly'=>true),
			array('zmi_title', 'length', 'max'=>100),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zmi_val','length','min'=>1),
			array('zo_id','safe'),
			array('zmi_id, zm_id, zti_id, zmi_val, zmi_condition,zmi_title, zmi_start_time, zmi_end_time, zmi_status', 'safe', 'on'=>'search'),
			array('zmi_status','in','range'=>array(1,2)),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'ticket'=> array(self::BELONGS_TO,'Ticket','zti_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zmi_id' => 'Id',
			'zm_id' => '会员ID',
			'zti_id' => '优惠券ID',
			'zmi_val' => '优惠券面值',
			'zmi_condition' => '使用条件金额',
			'zmi_title' => '优惠券名称',
			'zmi_start_time' => '开始时间',
			'zmi_end_time' => '结束时间',
			'zmi_status' => '是否有效',
			'inputtime' => '领取时间',
			'zo_id' => '订单ID',
		);
	}
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zmi_id',$this->zmi_id);
		$criteria->compare('zm_id',$this->zm_id);
		$criteria->compare('zti_id',$this->zti_id);
		$criteria->compare('zmi_val',$this->zmi_val);
		$criteria->compare('zmi_condition',$this->zmi_condition);
		$criteria->compare('zmi_title',$this->zmi_title,true);
		$criteria->compare('zmi_start_time',$this->zmi_start_time);
		$criteria->compare('zmi_end_time',$this->zmi_end_time);
		$criteria->compare('zmi_status',$this->zmi_status);
		$criteria->compare('inputtime',$this->inputtime);

		$criteria->order = " inputtime DESC ";//默认为时间倒序
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	/**
	 * 我的优惠券列表数据
	 * @return CActiveDataProvider 
	 */
	public function listSearch()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('t.zm_id',Yii::app()->user->userid);
		$criteria->compare('zmi_status',1);
		$criteria->with = 'ticket';
		$type = Yii::app()->request->getParam('type',0);
		if($type==1){
			$criteria->compare('zmi_start_time','<'.time());
			$criteria->compare('zmi_end_time','>'.time());
		}elseif($type==2){
			$criteria->compare('zmi_end_time','<'.time());
		}elseif($type==3){
			$criteria->compare('zmi_start_time','>'.time());
		}
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * 我的优惠券列表数据
	 * @params $price 订单金额
	 * @return array 
	 */
	public function getmyticketlist($price =0 )
	{
		$criteria=new CDbCriteria;

		$criteria->compare('t.zm_id',Yii::app()->user->userid);
		$criteria->compare('zmi_status',1);	
		if( $price!=0 )
		{
			$criteria->compare('zmi_condition','<'.$price);	
		}
		$criteria->compare('zmi_start_time','<'.time());
		$criteria->compare('zmi_end_time','>'.time());
		$model = $this->findAll($criteria);		
		return Chtml::listData($model,'zmi_id','zmi_title');
	}
	/*
	 *领取优惠券
	 *@params $zit_id 领取的优惠id
	 *@params $num    领取的优惠数量
	 */
	public function getTicket($zit_id,$num='1'){
	   $ticket = new Ticket;
	   $this->zti_id = $zit_id;
	   //获取已登录会员
	   $this->zm_id = Yii::app()->user->userid;   	   
	   //获取即将领取的优惠券详细
	   $ticketinfobyfk =  Ticket::model()->findByPk($this->zti_id); 
		   if($ticketinfobyfk===null){		   
				throw new CHttpException('没有相关数据');
		   }
	   //获取该会员的即将要领取的优惠券的历史记录
	   $condition = "zm_id='".$this->zti_id."' and zti_id = '".$this->zti_id."'";
	   $memticket = MemTicket::model()->findByAttributes(array('zm_id'=>$this->zm_id,'zti_id'=>$this->zti_id));
		   if($memticket==null){
			   $memticketnum = 0;
		   }else{
			   $memticketnum = $memticket->attributes['zmi_num'];
			   $memticket    = $memticket->attributes;
		   }
	   //判断领取权限
	   if($this->zm_id == $ticketinfobyfk['zm_id']){
		   throw new CHttpException(404,'不能领取自己发布的优惠券');
		   return false;
	   }else if($ticketinfobyfk['zti_status'] == '2'){
		   throw new CHttpException(404,'该活动已关闭');
	   }else if($ticketinfobyfk['zti_inventory'] < $num || $ticketinfobyfk['zti_inventory'] <= 0){		   
		   throw new CHttpException(404,'该优惠券剩余数量不够或者已领取完');
		   return false;
	   }else if ($ticketinfobyfk['zti_limitget'] < $num+$memticketnum){
		   throw new CHttpException(404,'该优惠券每人限领'.$ticketinfobyfk['zti_limitget']);
		   return false;
	   }else if($ticketinfobyfk['zti_start_time'] > time()){
		   throw new CHttpException(404,'还没到领取时间');
		   return false;
	   }else if($ticketinfobyfk['zti_end_time']  < time()){
		   throw new CHttpException(404,'领取时间已过');
		   return false;
	   }else{	
	       //如果之前没有领过该优惠券则新加一条记录，否则修改当前数量	 
	       if($memticketnum==0){
			   $this->zmi_title      = $ticketinfobyfk['zti_title'];
			   $this->zmi_val        = $ticketinfobyfk['zti_value'];
			   $this->zmi_start_time = $ticketinfobyfk['zti_start_time'];
			   $this->zmi_end_time   = $ticketinfobyfk['zti_end_time'];
			   $this->zmi_num        = $num;
			   $this->save();
		   }else{		     
		       $model=$this->model()->findByPk($memticket['zmi_id']);
		       $model->zmi_num   += $memticket['zmi_num'];
		       $model->inputtime =  time();
			   $model->save();
		   }
		   //修改优惠券剩余数量 		    		
		    $ticketinfobyfk->zti_inventory -=$num;
			$ticketinfobyfk->save();
			//添加领取记录
			$ticketlog 			  = new TicketLog();
			$ticketlog->zm_id 	  = $this->zm_id;
			$ticketlog->zti_id 	  = $this->zti_id;
			$ticketlog->ztl_type  = 1;
			$ticketlog->ztl_num   = $num;
			$ticketlog->ztl_price = $ticketinfobyfk['zti_value'];
			$ticketlog->inputtime = time();
			$ticketlog->save();
	   }	  
    }
    
	/**
	 * 删除会员优惠券
	 * $idbox id数组
	 * $memberid 会员id
	 * */
	public function deleteMemTicket($idbox, $memberid=null){
		$condition = 'zmi_id in('.implode(',', $idbox).')';
		if($memberid){
			$condition .= ' and zm_id='.$memberid;
		}
		return $this->updateAll(array('zmi_status'=>3),$condition);
	}
	
	
// 	protected function beforeSave(){
// 	    if (parent::beforeSave()){   
// 	        $this->inputtime  = time();  
// 	        $this->zmi_status = 2;  
// 	        return true;
// 	    }else{
// 	        return false;
// 	    }
// 	}
	
}